<?php

class Users extends Onecore_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model("users_model");
        $this->_moduleName = utf8_encode("Modulo users_model");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->users_model;
    }
    public function loadList(){
        $cfg = new stdClass();
        $cfg->start = $this->input->get('start');
        $cfg->limit = $this->input->get('limit');
        $cfg->conditions = new stdClass();
        $cfg->conditions->elem_questions_id = $this->input->get('question_id');
        $cfg->conditions->parent = 0;
        $cfg->orderField = 'description';
        $cfg->orderDirection = 'ASC';
        
        $data = $this->_modelInstance->listEntities($cfg);
        $res = array(
            "success" => true,
            "results" => $data['results'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function loadGrid() {
        $cfg = $this->config->item('defaultCfg');

        $options = new stdClass();
        $options->conditions = new stdClass();
        $options->start = $this->input->get('start');
        $options->limit = $this->input->get('limit');
        $options->conditions->deleted = $this->input->get('deleted');

        if (!$this->input->get('sort')) {
            $options->orderField = 'id';
            $options->orderDirection = 'DESC';
        } else {
            $orden = $this->input->get('sort');
            $sort = json_decode($orden);
            $options->orderField = $sort[0]->property;
            $options->orderDirection = $sort[0]->direction;
        }

        $data = $this->_modelInstance->loadListCrud($options);
        //$data = $this->_modelInstance->loadListCrud($options);

        //me evito una nueva query sql :D

        $res = array(
            "success" => true,
            "results" => $data['results'],
            "sql" => $data['sql'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function get(){
        $id = $this->input->post('id');
        $object = $this->_modelInstance->getByid($id);
        if(!empty($object[0]))
            $object = $object[0];
        $res = array(
            "success" => true,
            "data" => $object
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function add(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " creado en forma exitosa";
        $errorList = array();
        
        $names = $this->input->post('names');
        $lastnames = $this->input->post('lastnames');
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $phone = $this->input->post('phone');
        $address = $this->input->post('address');
        $status = $this->input->post('status');
        $professionId = $this->input->post('category_profession_id');
        $_rols_id = $this->input->post('_rols_id');
        
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $data = array(
                "id" => "",
                "data" => array(
                    'ucreated'=>$userEmail,
                    'names'=>$names,
                    'lastnames'=>$lastnames,
                    'email'=>$email,
                    'password'=>$password,
                    'phone'=>$phone,
                    'address' => $address,
                    'status' => $status,
                    'category_profession_id'=>$professionId,
                    "_rols_id" => $_rols_id
                )
            );
            
            if ($this->_modelInstance->save($data, false)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function edit(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        
        $id = $this->input->post('id');
        $names = $this->input->post('names');
        $lastnames = $this->input->post('lastnames');
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $phone = $this->input->post('phone');
        $address = $this->input->post('address');
        $status = $this->input->post('status');
        $professionId = $this->input->post('category_profession_id');
        $_rols_id = $this->input->post('_rols_id');

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $data = array(
                "id" => array(
                    'id'=>$id
                ),
                "data" => array(
                    'dmodified'=>date('Y-m-d H:i:s'),
                    'umodified'=>$userEmail,
                    'names'=>$names,
                    'lastnames'=>$lastnames,
                    'email'=>$email,
                    'password'=>$password,
                    'phone'=>$phone,
                    'address' => $address,
                    'status' => $status,
                    'category_profession_id'=>$professionId,
                    "_rols_id" => $_rols_id
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function del(){
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $id = $this->input->post('id');
        $object = $this->_modelInstance->getByid($id);
      
        
        if(is_array($object)) $object = $object[0];
        
        if(!empty($object)){
            $data = array(
                "id" => array(
                    'id'=>$id
                ),
                "data" => array(
                    'deleted'=>1
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $mensaje = "Usuario eliminado en forma existosa";
                $success = true;
            } else {
                $mensaje = "El objeto no puedo ser eliminado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
}